#include "eeprom.h"
#include "i2c.h"
#include "systimer.h"
#include <stdio.h>
#include <string.h>
#include "system.h"

void eeprom_write_one_byte(const uint8_t addr, const uint8_t data)
{
	i2c1_start();
	i2c1_send_byte(EEPROM_OPS_WRITE);
	i2c1_wait_ack();
	i2c1_send_byte(addr);
	i2c1_wait_ack();
	i2c1_send_byte(data);
	i2c1_wait_ack();
	i2c1_stop();
	delay_ms(5);
}

static void eeprom_write_one_page(const uint8_t addr, const uint8_t* const buf)
{
	i2c1_start();
	i2c1_send_byte(EEPROM_OPS_WRITE);
	i2c1_wait_ack();
	i2c1_send_byte(addr);
	i2c1_wait_ack();
	for(uint8_t i = 0; i < EEPROM_PAGE_SIZE; i++)
	{
		i2c1_send_byte(*(buf + i));
		i2c1_wait_ack();
	}
	i2c1_stop();
	delay_ms(5);
}

void eeprom_write_bytes(const uint16_t addr, const uint8_t* const buf, const uint16_t len)
{
	uint16_t pageSize = len / EEPROM_PAGE_SIZE;
	uint16_t remainSize = len % EEPROM_PAGE_SIZE;
	uint16_t addr2Write = addr;
	for(uint16_t i = 0; i < pageSize; i++)
	{
		eeprom_write_one_page(addr2Write, buf + i * EEPROM_PAGE_SIZE);
		addr2Write += EEPROM_PAGE_SIZE;
	}
	for(uint8_t i = 0; i < remainSize; i++)
	{
		eeprom_write_one_byte(addr2Write, buf[pageSize * EEPROM_PAGE_SIZE + i]);
		addr2Write++;
	}
}

void eeprom_read_bytes(const uint8_t addr, uint8_t* const buf, const uint16_t len)
{
	uint16_t i;
	i2c1_start();
	i2c1_send_byte(EEPROM_OPS_WRITE);
	i2c1_wait_ack();
	i2c1_send_byte(addr);
	i2c1_wait_ack();
	i2c1_start();
	i2c1_send_byte(EEPROM_OPS_READ);
	i2c1_wait_ack();
	for(i = 0; i < len - 1; i++)
	{
		*(buf + i) = i2c1_read_byte();
		i2c1_ack();
	}
	*(buf + i) = i2c1_read_byte();
	i2c1_nack();
	i2c1_stop();
}

 void eeprom_self_test(void)
 {
 	uint8_t sendBuf[256];
 	uint8_t readBuf[256];
	uint8_t sendByte = 0xA1;
	uint8_t readByte = 0;
	/* 单字节读写测试 */
	eeprom_write_one_byte(0, sendByte);
	eeprom_read_bytes(0, &readByte, 1);
	if(sendByte == readByte)
	{
		debug("single read & write successed\r\n");
	}
 	/* 页读写测试 */
 	for(uint16_t i = 0; i < 256; i++)
 	{
 		sendBuf[i] = i;
 	}
	for(uint16_t i = 0; i < 256 / 8; i++)
	{
		eeprom_write_one_page(8 * i, &sendBuf[8 * i]);
	}
	eeprom_read_bytes(0, readBuf, sizeof(readBuf));
	if(memcmp(readBuf, sendBuf, sizeof(readBuf)) == 0)
	{
		debug("page read & write successed\r\n");
	}
	/* 随机读写测试 */
	memset(readBuf, 0, sizeof(readBuf));
 	eeprom_write_bytes(0, (uint8_t *)sendBuf, sizeof(sendBuf));
	eeprom_read_bytes(0, readBuf, sizeof(readBuf));
	if(memcmp(readBuf, sendBuf, sizeof(readBuf)) == 0)
	{
		debug("random read & write successed\r\n");
	}
 }
